package com.bs.visitservice.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bs.visitservice.cache.impl.JedisLoginCache;
import com.bs.visitservice.entity.Admin;
import com.bs.visitservice.service.AdminService;
import com.bs.visitservice.utils.JwtUtil;
import com.bs.visitservice.utils.Result;
import com.bs.visitservice.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
@RestController
public class AdminLoginController {

    @Autowired
    private JedisLoginCache jedisLoginCache;
    @Autowired
    private AdminService adminService;
    /**
     * 商家登陆，返回tokenId
     * @param request
     * @param cond
     * @return
     */
    @RequestMapping(value = "/adminpublic/login",method = RequestMethod.POST)
    public Result login(HttpServletRequest request, @RequestBody Map cond){
        String verifyCode = (String)request.getSession().getAttribute("verifyCode");
        String pageVerifyCode = (String)cond.get("verifyCode");
        if(!verifyCode.equalsIgnoreCase(pageVerifyCode)){
            return Result.error("验证码不正确，请重新输入！");
        }
        Admin admin =  (Admin) ResultUtil.transObject(cond,Admin.class);
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getAccount,admin.getAccount()).eq(Admin::getPassword,admin.getPassword());
        List<Admin> adminLoginInfoList = adminService.list(wrapper);
        if(adminLoginInfoList.size() > 0){
            admin = adminLoginInfoList.get(0);
            Map<String,Object> claims = new HashMap<>();
            claims.put("loginNo",admin.getNo());
            claims.put("role","admin");
            Calendar c = Calendar.getInstance();
            c.add(Calendar.YEAR,1);
            //生成token
            String tokenId = JwtUtil.genToken(claims,c.getTime());
            //设置商家端tokenId失效时间30分钟
            jedisLoginCache.putCache(tokenId,admin.getNo(),30*60);
            List<Map<String,Object>> data = new ArrayList<>();
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("tokenId", tokenId);
            data.add(dataMap);
            return Result.success(data);
        }
        return Result.error(null);

    }
    /**
     * 商家端退出
     */
    @RequestMapping(value = "/admin/logout",method = RequestMethod.POST)
    public Result logout(HttpServletRequest request){
        String tokenId = request.getHeader("tokenId");
        boolean isSuc = jedisLoginCache.removeCache(tokenId);
        if(isSuc){
            return Result.success(null);
        }
        return Result.error(null);
    }
}
